package com.lxu.util;

import org.apache.poi.xwpf.usermodel.*;

import java.util.List;

public class InsertRowUtils {

    /**
     * @param table
     * @param rowIndex
     */
    public static void insertRow(XWPFTable table, int rows, int rowIndex) {
        XWPFTableRow copyRow = table.getRow(rowIndex);
        table.addRow(copyRow, rowIndex + 1);
    }


    /**
     * insertRow 在word表格中指定位置插入一行，并将某一行的样式复制到新增行
     *
     * @param copyrowIndex 需要复制的行位置
     * @param newrowIndex  需要新增一行的位置
     */
    public static void insertAndCopyRow(XWPFTable table, int copyrowIndex, int newrowIndex) {
        // 在表格中指定的位置新增一行
        XWPFTableRow targetRow = table.insertNewTableRow(newrowIndex);
        // 获取需要复制行对象
        XWPFTableRow copyRow = table.getRow(copyrowIndex);
        //复制行对象
        targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());
        //或许需要复制的行的列
        List<XWPFTableCell> copyCells = copyRow.getTableCells();
        //复制列对象
        XWPFTableCell targetCell = null;
        for (int i = 0; i < copyCells.size(); i++) {
            XWPFTableCell copyCell = copyCells.get(i);
            targetCell = targetRow.addNewTableCell();
            targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());
            if (copyCell.getParagraphs() != null && copyCell.getParagraphs().size() > 0) {
                targetCell.getParagraphs().get(0).getCTP().setPPr(copyCell.getParagraphs().get(0).getCTP().getPPr());
                if (copyCell.getParagraphs().get(0).getRuns() != null
                        && copyCell.getParagraphs().get(0).getRuns().size() > 0) {
                    XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();
                    cellR.setBold(copyCell.getParagraphs().get(0).getRuns().get(0).isBold());
                }
            }
        }
    }

    public static void insertTable(XWPFTable table, List<List<String>> tableList, Integer startRow, Integer totalRow) {
        //遍历表格插入数据
        List<XWPFTableRow> rows = table.getRows();
        for (int i = startRow; i < rows.size(); i++) {
            XWPFTableRow newRow = table.getRow(i);
            List<XWPFTableCell> cells = newRow.getTableCells();
            for (int j = 0; j < cells.size(); j++) {
                XWPFTableCell cell = cells.get(j);
                // cell.setText(tableList.get(i-1).get(j));
                XWPFParagraph xwpfParagraph = cell.getParagraphs().get(0);//获取cell中的第一个段落第一个ruan并设置字体样式和内容
                XWPFRun run = xwpfParagraph.createRun();
                run.setFontSize(9);
                run.setFontFamily("宋体");
                run.setText(tableList.get(i - 1).get(j));
            }
        }
    }
}
